# crudsystem.py
import peewee
from datetime import datetime

# 1. 初始化数据库连接
db = peewee.SqliteDatabase('data.db')


# 2. 定义数据模型
class BaseModel(peewee.Model):
    class Meta:
        database = db


class User(BaseModel):
    username = peewee.CharField(max_length=50, unique=True)
    email = peewee.CharField(max_length=100)
    created_at = peewee.DateTimeField(default=datetime.now)
    is_active = peewee.BooleanField(default=True)


# 3. 数据库初始化函数
def initialize_db():
    try:
        db.connect()
        db.create_tables([User], safe=True)
        print("[+] 数据库连接成功，表结构已创建")
    except peewee.OperationalError as e:
        print(f"[-] 数据库连接失败: {e}")
    finally:
        db.close()


# 4. CRUD 操作函数
def create_user(username, email):
    try:
        with db.transaction():
            user = User.create(
                username=username,
                email=email
            )
            print(f"[+] 创建用户成功: {user.username} (ID: {user.id})")
            return user
    except peewee.IntegrityError as e:
        print(f"[-] 创建失败: 用户名已存在或邮箱格式错误")


def get_all_users():
    try:
        users = User.select()
        if not users:
            print("[-] 当前没有用户记录")
            return
        print("\n[+] 用户列表:")
        for user in users:
            print(f"ID: {user.id}, 用户名: {user.username}, 邮箱: {user.email}, 创建时间: {user.created_at}")
    except peewee.OperationalError as e:
        print(f"[-] 数据库查询失败: {e}")


def update_user(user_id, new_username=None, new_email=None):
    try:
        with db.transaction():
            user = User.get(User.id == user_id)
            updated_fields = []

            if new_username:
                user.username = new_username
                updated_fields.append("用户名")
            if new_email:
                user.email = new_email
                updated_fields.append("邮箱")

            if updated_fields:
                user.save()
                print(f"[+] 更新成功: 已修改 {', '.join(updated_fields)}")
                return user
            else:
                print("[-] 未提供任何需要更新的字段")
    except peewee.DoesNotExist:
        print(f"[-] 用户不存在: ID {user_id}")
    except peewee.IntegrityError as e:
        print(f"[-] 更新失败: {e}")


def delete_user(user_id):
    try:
        with db.transaction():
            user = User.get(User.id == user_id)
            user.delete_instance()
            print(f"[+] 用户已删除: {user.username} (ID: {user_id})")
    except peewee.DoesNotExist:
        print(f"[-] 用户不存在: ID {user_id}")


# 5. 主控制台循环
def main():
    initialize_db()

    while True:
        print("\n=== 用户管理系统 ===")
        print("1. 创建用户")
        print("2. 查看所有用户")
        print("3. 更新用户信息")
        print("4. 删除用户")
        print("5. 退出系统")

        choice = input("\n请选择操作(1-5): ").strip()

        if choice == '1':
            username = input("请输入用户名: ").strip()
            email = input("请输入邮箱: ").strip()
            create_user(username, email)

        elif choice == '2':
            get_all_users()

        elif choice == '3':
            user_id = input("请输入要更新的用户ID: ").strip()
            new_username = input("新用户名(留空保持不变): ").strip()
            new_email = input("新邮箱(留空保持不变): ").strip()
            update_user(user_id, new_username if new_username else None, new_email if new_email else None)

        elif choice == '4':
            user_id = input("请输入要删除的用户ID: ").strip()
            delete_user(user_id)

        elif choice == '5':
            print("[+] 正在退出系统...")
            break

        else:
            print("[-] 无效的输入，请重新选择")


if __name__ == "__main__":
    main()
